package com.hzcx.app.simplechat.ui.group;

import android.util.Log;
import android.view.View;

import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hzcx.app.simplechat.api.BaseObserver;
import com.hzcx.app.simplechat.base.BaseEmptyBean;
import com.hzcx.app.simplechat.chat.ChatUtil;
import com.hzcx.app.simplechat.model.GroupModel;
import com.hzcx.app.simplechat.ui.chat.GroupContactManageActivity;
import com.hzcx.app.simplechat.ui.friend.FriendListByLableActivity;
import com.hzcx.app.simplechat.ui.friend.bean.FriendBean;
import com.hzcx.app.simplechat.ui.friend.bean.FriendCityBean;
import com.hzcx.app.simplechat.ui.friend.bean.GroupBean;
import com.hzcx.app.simplechat.ui.group.LiveData.GroupInfoBeanLiveData;
import com.hzcx.app.simplechat.ui.group.adapter.GroupMembersSort;
import com.hzcx.app.simplechat.ui.group.bean.GroupCreateBean;
import com.hzcx.app.simplechat.ui.group.bean.GroupInfoBean;
import com.hzcx.app.simplechat.ui.group.bean.MembersBean;
import com.hzcx.app.simplechat.ui.publicui.PublicTipsDialog;
import com.hzcx.app.simplechat.ui.publicui.bean.HxUserInfoBean;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.log.LogUtils;

import java.security.acl.Group;
import java.util.ArrayList;
import java.util.List;

import indi.liyi.viewer.Utils;

public class GroupDeleteMemberActivity extends FriendListByLableActivity implements PublicTipsDialog.OnPublicTipsClickListener {

    static public String GroupCreateActivityGroupID = "GroupCreateActivityGroupID";
    public String groupID;

    // 记录初始时已选中的成员数
    int originCheckNum = 0;
    @Override
    public void initView() {
        super.initView();
        swipeToLoadLayout.setLoadMoreEnabled(false);
        tvTitleRight.setVisibility(View.GONE);
        ivTitleRight.setVisibility(View.GONE);
//        tagAction = getIntent().getIntExtra(GroupCreateActivityTagAction, 0);
        groupID = getIntent().getStringExtra(GroupCreateActivityGroupID);

        friendAdapter.setOnFriendListItemOnClickListener((headerPos, contentPos, id, bean) -> {
            if (hasCheck(bean)) {
                return;
            }
            if (this instanceof GroupManagerDeleteActivity){
                friendData.get(headerPos-1).getCity().get(contentPos).setChecked(!friendData.get(headerPos-1).getCity().get(contentPos).isChecked());
            }else {
                friendData.get(headerPos).getCity().get(contentPos).setChecked(!friendData.get(headerPos).getCity().get(contentPos).isChecked());
            }
            friendAdapter.notifyDataSetChanged();
            setCheckedNum();
        });
    }

    @Override
    public void initData() {
        mPresenter.getFriendList(this);
        addGroupCreateHeader();
    }

    /**
     * 原始成员列表是否已经包含对应的好友
     */
    public boolean hasCheck(FriendCityBean bean) {
        GroupInfoBean groupInfoBean = GroupInfoBeanLiveData.getGroupInfoBean(groupID);
        if (groupInfoBean == null || groupInfoBean.getMembers() == null) {
            return false;
        }
        List<MembersBean> originMembers = groupInfoBean.getMembers();
        for (MembersBean membersBean : originMembers) {
            if (membersBean.getMember_id() == bean.getMember_id()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 设置默认选中的好友
     */
    public void setDefaultCheckedData() {
        GroupInfoBean groupInfoBean = GroupInfoBeanLiveData.getGroupInfoBean(groupID);
        if (groupInfoBean == null || groupInfoBean.getMembers() == null) {
            return;
        }
        List<MembersBean> originMembers = groupInfoBean.getMembers();

        for (FriendBean friendBean: friendData) {
            for (FriendCityBean friendCityBean : friendBean.getCity()) {
                for (MembersBean membersBean : originMembers) {
                    if (membersBean.getMember_id() == friendCityBean.getMember_id()) {
                        friendCityBean.setChecked(true);
                        originCheckNum++;
                        continue;
                    }
                }
            }
        }
    }

    /**
     * 下一步
     */
    @Override
    public void toNext() {
//        if (setCheckedNum() <= 0) {
//            showError("请选择好友");
//            return;
//        }
        finishAction(friendData);
    }

    /**
     * 获取选中总人数
     */
    @Override
    public int setCheckedNum() {
        int num = 0;
        for (FriendBean bean : friendData) {
            if (bean == null || bean.getCity() == null || bean.getCity().size() <= 0) {
                continue;
            }
            for (FriendCityBean subBean : bean.getCity()) {
                if(subBean.isChecked()) {
                    num++;
                }
            }
        }
        int newCount = num - originCheckNum;
        if (newCount > 0) {
            tvNext.setText("完成(" + newCount + ")");
        } else {
            tvNext.setText("完成");
        }
        return newCount;
    }


    @Override
    public void finishAction(List<FriendBean> beans) {
        String ids = "";

        List<MembersBean> originMembers;
        GroupInfoBean groupInfoBean = GroupInfoBeanLiveData.getGroupInfoBean(groupID);
        if (groupInfoBean == null || groupInfoBean.getMembers() == null) {
            originMembers = new ArrayList<>();
        } else {
            originMembers = groupInfoBean.getMembers();
        }

        for (FriendBean friendBean: friendData) {
            for (FriendCityBean friendCityBean : friendBean.getCity()) {
                if (!friendCityBean.isChecked()) {
                    continue;
                }
                boolean neddAdd = true;
                for (MembersBean membersBean : originMembers) {
                    if (membersBean.getMember_id() == friendCityBean.getMember_id()) {
                        neddAdd = false;
                        continue;
                    }
                }
                if (neddAdd) {
                    ids += friendCityBean.getMember_id() + ",";
                }
            }
        }

        if (ids.length() > 1) {
            ids = ids.substring(0, ids.length() - 1);
        }
        Log.i("createGroup", "create group ids : " + ids);
        showLoading();
        if (groupID != null && !groupID.isEmpty()) {
            inviteGroupMember(groupID, ids);
        } else {
            createGroup(ids);
        }
    }

    private void inviteGroupMember(String groupID, String ids) {

        GroupModel.inviteGroupMember(this, groupID, ids, new BaseObserver<BaseEmptyBean>() {
            @Override
            protected void onSuccess(BaseEmptyBean data) {
                GroupModel.getGroupInfo(GroupDeleteMemberActivity.this, groupID, new BaseObserver<GroupInfoBean>() {
                    @Override
                    protected void onSuccess(GroupInfoBean data) {
                        data.setMembersCount(data.getMembers().size());
                        data.save();
                        GroupInfoBeanLiveData.update(data);
                        hideLoading();
                        finish();
                    }
                    @Override
                    public void onFailure(Throwable e, String errorMsg) {
                        hideLoading();
                        PublicTipsDialog confirmDialog = new PublicTipsDialog(GroupDeleteMemberActivity.this, "提示", errorMsg, GroupDeleteMemberActivity.this);
                        confirmDialog.show();
                    }
                });
            }
            @Override
            public void onFailure(Throwable e, String errorMsg) {
                hideLoading();
                PublicTipsDialog confirmDialog = new PublicTipsDialog(GroupDeleteMemberActivity.this, "提示", errorMsg, GroupDeleteMemberActivity.this);
                confirmDialog.show();
            }
        });
    }

    private void createGroup(String ids) {
        GroupModel.createGroup(this, ids, new BaseObserver<GroupCreateBean>() {
            @Override
            protected void onSuccess(GroupCreateBean data) {

                GroupModel.getGroupInfo(GroupDeleteMemberActivity.this, data.getGroup_id(), new BaseObserver<GroupInfoBean>() {
                    @Override
                    protected void onSuccess(GroupInfoBean data) {
                        data.setMembersCount(data.getMember_total());
                        data.save();
                        GroupInfoBeanLiveData.update(data);
                        hideLoading();
                        data.save();

                        Log.i("createGroup", "create group cloud success : " + data.toString());
                        Log.i("createGroup", "hx groupid : " + data.getHx_groupid());
                        String hx_groupid = data.getHx_groupid();
                        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(hx_groupid, EMConversation.EMConversationType.GroupChat, true);
                        if (conversation == null) {
                            Log.i("createGroup", "create hx conversation : null");
                        } else {
                            Log.i("createGroup", "hx conversation : " + conversation);
                        }
                        // FIXME: 跳转群聊天界面
                        finish();

                        // 是好友，直接聊天
                        HxUserInfoBean hxUserInfoBean = new HxUserInfoBean();
                        hxUserInfoBean.setHxusername(data.getHx_groupid());
                        hxUserInfoBean.setMember_id(Integer.valueOf(data.getGroup_id()));
                        hxUserInfoBean.setNickname(data.getGroup_name());
                        hxUserInfoBean.setAvatar(data.getGroup_image());
                        hxUserInfoBean.setBy_remarks_name(data.getGroup_desc());
                        hxUserInfoBean.setBy_remarks_name("");
                        hxUserInfoBean.setRemarks_name(data.getGroup_name());
                        hxUserInfoBean.setMyUserId(UserInfoUtil.getUserId());
                        hxUserInfoBean.setIs_assistant(0);
                        ChatUtil.getInstance().toGroupChatUi(GroupDeleteMemberActivity.this, hxUserInfoBean);
                    }

                    @Override
                    public void onFailure(Throwable e, String errorMsg) {
                        hideLoading();
                        PublicTipsDialog confirmDialog = new PublicTipsDialog(GroupDeleteMemberActivity.this, "提示", errorMsg, GroupDeleteMemberActivity.this);
                        confirmDialog.show();
                    }
                });
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                hideLoading();
                PublicTipsDialog confirmDialog = new PublicTipsDialog(GroupDeleteMemberActivity.this, "提示", errorMsg, GroupDeleteMemberActivity.this);
                confirmDialog.show();
            }
        });
    }

    @Override
    public void publicTips() {

    }
}